package com.zhj.common.swagger;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.zhj.common.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger2Config.class)
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    // swagger2的配置文件，这里可以配置swagger2的一些基本的内容，比如扫描的包等等
    @Bean
    public Docket createRestApi(Swagger2Config swagger2Config) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(swagger2Config))
                .select()
                // 为当前包路径
                .apis(this.basePackage(swagger2Config.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
    }

    // 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo(Swagger2Config swagger2Config) {
        return new ApiInfoBuilder()
                // 页面标题
                .title(swagger2Config.getTitle())
                // 创建人信息
                .contact(swagger2Config.getContact().build())
                // 版本号
                .version(swagger2Config.getVersion())
                // 描述
                .description(swagger2Config.getDescription())
                .build();
    }

    public Predicate<RequestHandler> basePackage(String basePackage) {
        return input -> Optional.fromNullable(input.declaringClass())
                .transform((Function<Class<?>, Boolean>) input1 -> StringUtil.match(basePackage, ClassUtils.getPackageName(input1)))
                .or(false);
    }


}
